/*
 * Task.cpp
 *
 *  Created on: 03.12.2012
 *      Author: zheka
 */

#include "Task.hpp"
#include "util/ProxyException.hpp"
#include "util/Log.hpp"
#include "util/StringUtils.hpp"
const int Task::BUFFER_SIZE = 1024;

std::vector<Task*>  Task::instances ;
Task::Task() :
		fileDescriptor(-1) {
	instances.push_back(this);
	Log::v(StringUtils::toString((int)this)+" !!!! new Task() unknown ["+StringUtils::toString(getFileDiscriptor())+"] count="+StringUtils::toString(instances.size()));
		//Log::v("!!!! new Task() count="+StringUtils::toString(instances.size()));
}
int Task::getFileDiscriptor() {
	return fileDescriptor;
}
void Task::setFileDiscriptor(int fileDescriptor) {
	Log::v(StringUtils::toString((int)this)+" setFileDiscriptor ["+StringUtils::toString(fileDescriptor)+"]");
	this->fileDescriptor = fileDescriptor;
}
std::string Task::read(const int bufferSize = Task::BUFFER_SIZE) {
	char buffer[bufferSize];
	int count = 0;
	if ((count = ::read(fileDescriptor, buffer, sizeof(buffer))) < 0) {
		throw ProxyException(
				"[Task] IO error has occurred while attempting to read the data!");
	}
//	if (count == 0) {
//		throw ProxyException("[Task] End of file!");
//	}
	return std::string(buffer, count);
}

std::string Task::write(const std::string & source) {

	int count = 0;
	if ((count = ::write(fileDescriptor, source.c_str(), source.length()))
			== 0) {
		throw ProxyException(
				"[Task] IO error has occurred while attempting to write the data!");
	}

	return source.substr(count);
}
#include <signal.h>
size_t Task::write(const std::string & source, size_t offset = 0) {
	//signal(SIGPIPE, SIG_IGN);
	/*if(signal(SIGPIPE, SIG_IGN) == SIG_ERR)  {
Log::v("cant set handler");
	}*/
	if (source.length() - offset <= 0) {
		return 0;
	}
	int count = 0;
	if ((count = ::write(fileDescriptor, source.c_str() + offset,
			source.length() - offset)) <= 0) {
		throw ProxyException(
				"[Task] IO error has occurred while attempting to write the data!");
	}


	return count;
}
void Task::onDestroy(Context & context) {
	context.disableRead();
	context.disableWrite();
	close(fileDescriptor);
	Log::v("[Task] onDestroy of ["+StringUtils::toString(fileDescriptor)+"]");
}
std::string Task::toString() {
	return "["+StringUtils::toString(getFileDiscriptor())+"]";
}
